package com.woniuxy.search.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniuxy.common.model.dto.PageDto;
import com.woniuxy.search.model.entity.Stu;
import com.woniuxy.search.service.SearchService;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SearchServiceImpl implements SearchService {
    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;
    @Override
    public Page<Stu> search(PageDto pageDto) {
        String keyword = pageDto.getInfo();
        int page = pageDto.getPage();
        int size = pageDto.getSize();

        // 构建查询条件
        Query query = new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.matchQuery("info", keyword)) // 使用 info 字段进行查询
                .withPageable(PageRequest.of(page - 1, size))          // 设置分页
                .build();

        // 执行查询
        SearchHits<Stu> searchHits = elasticsearchRestTemplate.search(query, Stu.class);

        // 获取查询结果内容
        List<Stu> content = searchHits.stream()
                .map(hit -> hit.getContent())  // 获取每个查询命中的 Stu 对象
                .collect(Collectors.toList());

        // 获取总命中数
        long total = searchHits.getTotalHits();

        // 构建分页对象并返回
        Page<Stu> resultPage = new Page<>(page, size, total);
        resultPage.setRecords(content);
        return resultPage;
    }
}
